import Ajax from "./ajax"
import Api from "./api"

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/* base64 转换为图片 */
function base64src(base64data, fileName, cb) {
	const fsm = wx.getFileSystemManager();
	const FILE_BASE_NAME = 'tmp_base64src'+fileName; //自定义文件名
  const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64data) || [];
  if (!format) {
    return (new Error('ERROR_BASE64SRC_PARSE'));
  }
  const filePath = `${wx.env.USER_DATA_PATH}/${FILE_BASE_NAME}.${format}`;
  const buffer = wx.base64ToArrayBuffer(bodyData);
  fsm.writeFile({
    filePath,
    data: buffer,
    encoding: 'binary',
    success() {
      cb(filePath);
    },
    fail() {
      return (new Error('ERROR_BASE64SRC_WRITE'));
    },
  });
};

/* 获取图片 */
function getImg(url){
	return new Promise((resolve, reject) => {
		wx.getImageInfo({
		  src: url,
		  success(res) {
			 resolve(res.path)
		  },
		  fail(res){
			  reject(res)
		  }
		})
	})
}

// 登录 （异步）
function loginwx() {
  return new Promise(function (reslove, reject) {
    let openid = wx.getStorageSync('openid');
    if(openid){
      reslove(openid);
    }else{
      wx.login({
        success(res) {
          wx.setStorageSync("loginCode", res.code);
          Ajax.get(Api.wx.getOpenid,{code: res.code}).then(data=>{
            let nd = JSON.parse(data)
            wx.setStorageSync('openid', nd.openid)
            reslove(nd.openid);
          })
        },
      });
    }
  });
}

// 判断对象是否为空
function isEmpty (obj) {
  if (typeof obj == 'number') {
    obj = obj.toString();
  }
  if (obj == '[]') return true;
  // 本身为空直接返回true
  if (obj == null) return true;
  // 然后可以根据长度判断，在低版本的ie浏览器中无法这样判断。
  if (obj.length > 0) return false;
  if (obj.length === 0) return true;
  // 最后通过属性长度判断。
  for (let key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) return false;
  }
  return true;
}

module.exports = {
  formatTime: formatTime,
  base64src: base64src,
  getImg:getImg,
  loginwx: loginwx,
  isEmpty: isEmpty
}
